package net.mayee.alice.web.controller.admin.system;

import net.mayee.alice.entity.menu.sidebar.SidebarMenu;
import net.mayee.alice.entity.permission.Action;
import net.mayee.alice.web.controller.base.BaseController;
import net.mayee.common.MenuHelper;
import net.mayee.common.PermissionHelper;
import net.mayee.datatables.DtBean;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
public class PermissionController extends BaseController {

    @RequiresPermissions(value = {"permission:R"})
    @RequestMapping(value = "/sdm/sys/perm/R")
    public String permissionR(Model model) {
        model.addAttribute("sbmList",MenuHelper.getInstance().getSidebarMenus().getSidebarMenu());
        return "system/permission/permissionR";
    }

    @RequiresPermissions(value = {"permission:R"})
    @RequestMapping(value = "/sys/perm/ajax/R")
    public void permissionRAjax(HttpServletResponse response, HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        JSONArray array = new JSONArray();
        DtBean dtBean = new DtBean(request);

        /* 收集所有菜单国际化信息，以id-msgKey组成键值对 */
        HashMap<String, String> menuId_MsgKeyHM = new HashMap<String, String>();
        List<SidebarMenu> sbmList = MenuHelper.getInstance().getSidebarMenus().getSidebarMenu();
        for(SidebarMenu sbm : sbmList){
            menuId_MsgKeyHM.put(sbm.getId(), sbm.getMessageKey());

            List<SidebarMenu> subMList = sbm.getSubMenuList();
            for(SidebarMenu subM : subMList){
                menuId_MsgKeyHM.put(subM.getId(), subM.getMessageKey());
            }
        }

        int totalRecords = PermissionHelper.getInstance().getPermissionCount();
        int totalDisplayRecords = totalRecords;
        List<Action> list = PermissionHelper.getInstance().searchByLimit(dtBean.getSearchParams());
        if (dtBean.isHasSearch()) {
            totalDisplayRecords = list.size();
        }
        for(Action action : list){
            JSONArray ja = new JSONArray();
            String menuId = action.getMenuId();
            String actionName = action.getMenuName();
            if(menuId_MsgKeyHM.containsKey(menuId)){
                ja.put(this.getMessage(menuId_MsgKeyHM.get(menuId), actionName));
            }else{
                ja.put(actionName);
            }
            ja.put(menuId);
            ja.put(action.getText());
            ja.put(action.getKey());
            ja.put(action.getNote());
            array.put(ja);
        }
        request.setAttribute("reJSON", dtBean.getJSONString(array, totalRecords, totalDisplayRecords));
    }

}
